import axios from 'axios'

const API_URL = 'http://localhost:8080'

const api = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json'
  },
  // 确保跨域请求时携带凭证
  withCredentials: false
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.log('发送请求:', config.url, config.data)
    const user = JSON.parse(localStorage.getItem('user'))
    if (user && user.token) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('响应成功:', response.config.url, response.data)
    return response
  },
  error => {
    console.error('响应错误:', error.config?.url, error.message)
    return Promise.reject(error)
  }
)

// 用户相关API
export const userApi = {
  register: (userData) => {
    console.log('发送注册请求:', userData);
    return api.post('/users', userData);
  },
  login: (username, password) => {
    console.log('发送登录请求:', { username, password });
    return api.post('/users/login', { username, password });
  },
  getAllUsers: () => api.get('/users'),
  getUserById: (id) => api.get(`/users/${id}`),
  updateUser: (id, userData) => api.put(`/users/${id}`, userData),
  deleteUser: (id) => api.delete(`/users/${id}`)
}

// 会议室相关API
export const roomApi = {
  getAllRooms: () => api.get('/rooms'),
  getAvailableRooms: () => api.get('/rooms/available'),
  getRoomById: (id) => api.get(`/rooms/${id}`),
  getRoomsByCapacity: (capacity) => api.get(`/rooms/capacity/${capacity}`),
  addRoom: (roomData) => api.post('/rooms', roomData),
  updateRoom: (id, roomData) => api.put(`/rooms/${id}`, roomData),
  deleteRoom: (id) => api.delete(`/rooms/${id}`)
}

// 时间格式化辅助函数
export const timeUtils = {
  // 格式化日期时间为ISO 8601格式
  toISOString(date) {
    if (!date) return null;
    // 确保是Date对象
    const dateObj = date instanceof Date ? date : new Date(date);
    return dateObj.toISOString();
  },
  
  // 解析ISO 8601格式为本地日期时间
  fromISOString(isoString) {
    if (!isoString) return null;
    return new Date(isoString);
  },
  
  // 格式化为本地显示格式
  formatLocal(date) {
    if (!date) return '';
    // 确保是Date对象
    const dateObj = date instanceof Date ? date : new Date(date);
    return dateObj.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
  }
};

// 预约相关API
export const reservationApi = {
  getAllReservations: () => api.get('/reservations'),
  getReservationById: (id) => api.get(`/reservations/${id}`),
  getUserReservations: (userId) => api.get(`/reservations/user/${userId}`),
  getRoomReservations: (roomId) => api.get(`/reservations/room/${roomId}`),
  getReservationsByStatus: (status) => api.get(`/reservations/status/${status}`),
  createReservation: (reservationData) => api.post('/reservations', reservationData),
  updateReservation: (id, reservationData) => api.put(`/reservations/${id}`, reservationData),
  deleteReservation: (id) => api.delete(`/reservations/${id}`),
  approveReservation: (id) => api.put(`/reservations/${id}/approve`),
  rejectReservation: (id) => api.put(`/reservations/${id}/reject`),
  cancelReservation: (id) => api.put(`/reservations/${id}/cancel`),
  checkTimeConflict: (roomId, startTime, endTime, roomName) => {
    console.log('发送检查时间冲突请求:', { roomId, startTime, endTime, roomName });
    return api.post('/reservations/check-conflict', { roomId, startTime, endTime, roomName })
      .then(response => {
        console.log('时间冲突检查响应成功:', response.data);
        return response;
      })
      .catch(error => {
        console.error('时间冲突请求错误:', error);
        console.error('请求配置:', error.config);
        if (error.response) {
          console.error('响应状态:', error.response.status);
          console.error('响应数据:', error.response.data);
        }
        throw error;
      });
  },
  // 添加一个测试API调用
  testPost: (data) => api.post('/test/hello', data)
}

export default api 